package com.domor.service.system;

import com.domor.dao.system.DeptDao;
import com.domor.utils.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DeptService {

    @Autowired
    private DeptDao dao;

    public Map<String,Object> getById(int id) {
        return dao.getById(id);
    }

    public List<Map<String, Object>> query() {
        return getFatherDepts(dao.query());
    }
    private List<Map<String, Object>> getFatherDepts(List<Map<String, Object>> depts) {
        List<Map<String, Object>> resultDepts = new ArrayList<>();
        for(Map<String, Object> dept : depts) {
            int id = MapUtils.getIntValue(dept, "id");
            int pid = MapUtils.getIntValue(dept, "parentId");
            if(pid == 0) {
                List<Map<String, Object>> children = getChildrenDepts(id, depts);
                if (children != null && !children.isEmpty())
                    dept.put("children", children);
                resultDepts.add(dept);
            }
        }
        return resultDepts;
    }

    private List<Map<String, Object>> getChildrenDepts(int parentId, List<Map<String, Object>> depts) {
        List<Map<String, Object>> resultDepts = new ArrayList<>();
        for(Map<String, Object> dept : depts) {
            int id = MapUtils.getIntValue(dept, "id");
            int pid = MapUtils.getIntValue(dept, "parentId");
            if(pid == 0) continue;
            if(parentId == pid) {
                List<Map<String, Object>> children = getChildrenDepts(id, depts);
                if (children != null && !children.isEmpty())
                    dept.put("children", children);
                resultDepts.add(dept);
            }
        }
        return resultDepts;
    }

    public void insert(Map<String, Object> params){
        dao.insert(params);
    }

    public void update(Map<String, Object> params){
        dao.update(params);
    }

    public void delete(Map<String, Object> params){
        dao.delete(params);
    }

    public List<Integer> getChildrenDeptId(int id) {
        List<Integer> ids = new ArrayList<>();
        ids.add(id);
        getChildren(id, ids);
        return ids;
    }

    private void getChildren(int id, List<Integer> ids){
        List<Integer> deptIds = dao.getByParentId(id);
        ids.addAll(deptIds);
        for (Integer deptId : deptIds) {
            getChildren(deptId, ids);
        }
    }

    public int getChildrenDept(int id){
        return dao.getChildrenDept(id);
    }

    public int getChildrenUser(int id){
        return dao.getChildrenUser(id);
    }


}
